/**
 * Created by Administrator on 2015/6/15.
 */
var express = require('express');
var router = express.Router();

var Constants = require('../constants');
var mongoTemplate = require('../mongoTemplate');
var webutils = require('../webutils');
var model = require('../model');
var managerService = require('../services/managerService');
var BSON = require('mongodb').BSONPure;


router.get('/', function (req, res) {
    mongoTemplate.find(Constants.TABLE.ENV, {}, {}, function (err, docs) {
        if (err) {
            res.render('manager', {envs: []});
        } else {
            res.render('manager', {envs: docs});
        }
    });
});


router.get('/env', function (req, res) {
    mongoTemplate.find(Constants.TABLE.ENV, {}, {}, function (err, docs) {
        if (err) {
            res.send({status: "error"});
        } else {
            res.send({status: "ok", envs: docs});
        }
    });
});


router.put('/env', function (req, res) {
    var code = req.param("code");
    var name = req.param("name");
    var env = {code: code, name: name, status: 1};
    mongoTemplate._insert(Constants.TABLE.ENV, env, {}, function (err) {
        var result = null;
        if (err) {
            result = {status: "error"};
        } else {
            result = {status: "ok"};
        }
        res.send(result);
    });
});


router.delete('/env/:envId', function (req, res) {
    var envId = req.params.envId;
    var _envId = BSON.ObjectID.createFromHexString(envId);
    mongoTemplate._delete(Constants.TABLE.ENV, {"_id": _envId}, {}, function (err) {
        var result = null;
        if (err) {
            result = Constants.ERROR_RESULT;
        } else {
            result = Constants.OK_RESULT;
        }
        res.send(result);
    });

});


router.put("/host", function (req, res) {
    var host = new model.host();
    webutils.fillParam(req, host);
    //var _envId = BSON.ObjectID.createFromHexString(host.hostEnv);
    //host.hostEnv = new BSON.DBRef(Constants.TABLE.ENV, host.hostEnv);
    //if(host.hostParent){
    //    var _parentId = BSON.ObjectID.createFromHexString(host.hostParent);
    //    host.hostParent = new BSON.DBRef(Constants.TABLE.HOST, _parentId);
    //}
    console.log(host);
    mongoTemplate._insert(Constants.TABLE.HOST, host, {}, Constants.INSERT_CALLBACK_BASE(res));
});


router.get("/host",function(req, res){
    var envs = mongoTemplate.findSync(Constants.TABLE.ENV,{});
    mongoTemplate.find(Constants.TABLE.HOST, {}, {}, function (err, docs) {
        if (err) {
            res.send(Constants.ERROR_RESULT);
        } else {
            res.send({status: "ok", hosts: managerService.groupHosts(docs,envs)});
        }
    });
});

module.exports = router;